package houmen;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Client implements Runnable {

	private Socket s = null;
	private ClientWindow parent;
	public Client(ClientWindow parent) {
		this.parent = parent;
	}

	@Override
	public void run() {

		try {
			ServerSocket server = new ServerSocket (5656);
			while(true) {
				try {
					parent.appendln("正在监听");
					Socket soc = server.accept();
					this.s = soc;
					parent.appendln("有主机接入");
					new Printer( soc.getInputStream()).start();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 发送文件
	 * @param sf
	 */
	public void sendFile(File sf) {
		// TODO Auto-generated method stub

	}

	/**
	 * 发送命令
	 * @param text
	 * @throws IOException 
	 */
	public void sendCommand(String text){
		OutputStream os;
		try {
			os = s.getOutputStream();
			PrintStream op = new PrintStream(os);
			op.print(text);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	static class Printer extends Thread {
		InputStream is;
		public Printer(InputStream is) {
			this.is = is;
		}

		@Override
		public void run() {
			BufferedReader br = new BufferedReader(new InputStreamReader(is));

			while(true) {
				try {
					String line = br.readLine();
					line = new String(line.getBytes(), "utf-8");
					System.out.println(line);
				} catch (IOException e) {
				}
			}
		}
	}

}
